<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace battery\portal\controller;


use battery\portal\model\BatteryBaseModel;
use battery\portal\model\PingZfPlatform;
use battery\portal\model\SdPlatform;
use think\Config;
use think\Request;
use think\Validate;
class BrandController extends BatteryBaseController
{


    function index(){

        $this->setTitleName('自助选车');
       
        return $this->fetch();
    }


    function searchBrand(){

        $sdPlatform=new SdPlatform();
        $info=$sdPlatform->searchBrand();
        if($info['status']){
            $this->success('请求成功','',$info['info']);
        }else{
            $this->error('获取失败');
        }
    }

    function searchSeries(){
        $validate = new Validate([
            'name'          => 'require',
        ]);
        $validate->message([
            'name.require'          => '品牌名称',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $sdPlatform=new SdPlatform();
        $info=$sdPlatform->searchSeries(trim($data['name']));
        if($info['status']){
            $this->success('请求成功','',$info['info']);
        }else{
            $this->error('获取失败');
        }
    }

    function searchYear(){
        $validate = new Validate([
            'name'          => 'require',
            'type'          => 'require',
        ]);
        $validate->message([
            'name.require'          => '品牌名称',
            'type.require'          => '车辆类型',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $sdPlatform=new SdPlatform();
        $info=$sdPlatform->searchYear(trim($data['name']),trim($data['type']));
        if($info['status']){
            $this->success('请求成功','',$info['info']);
        }else{
            $this->error('获取失败');
        }
    }
    function searchModel(){
        $validate = new Validate([
            'name'          => 'require',
            'type'          => 'require',
            'year'          => 'require',
        ]);
        $validate->message([
            'name.require'          => '品牌名称',
            'type.require'          => '车辆类型',
            'year.require'          => '车辆类型',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $sdPlatform=new SdPlatform();
        $info=$sdPlatform->searchModel(trim($data['name']),trim($data['type']),trim($data['year']));
        if($info['status']){
            $this->success('请求成功','',$info['info']);
        }else{
            $this->error('获取失败');
        }
    }

    function goods(){
        $validate = new Validate([
            'name'          => 'require',
            'type'          => 'require',
            'year'          => 'require',
            'model'          => 'require',
            'carid'          => 'require',
        ]);
        $validate->message([
            'name.require'          => '品牌名称',
            'type.require'          => '车辆类型',
            'year.require'          => '车辆类型',
            'model.require'          => '车辆类型',
            'carid.require'          => '车辆类型',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $sdPlatform=new SdPlatform();
        $info=$sdPlatform->weblcMatch(trim($data['carid']));
        $sdata=array();
        if($info['status']){
            $sdata=$info['info'];
        }
        $this->setTitleName('电瓶上门安装');
        $this->assign('carname', trim($data['name']));
        $this->assign('cartype', trim($data['type']));
        $this->assign('caryear', trim($data['year']));
        $this->assign('carmodel', trim($data['model']));
        $this->assign('datalist', $sdata);

        return $this->fetch();
    }







function getpay(){
        $validate = new Validate([
            'name'          => 'require',
            'type'          => 'require',
            'year'          => 'require',
            'model'          => 'require',
            'gid'          => 'require',
        ]);
        $validate->message([
            'name.require'          => '品牌名称',
            'type.require'          => '车辆类型',
            'year.require'          => '车辆年份',
            'model.require'          => '车辆型号',
            'gid.require'          => '商品ID',
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $batteryBaseModel = new BatteryBaseModel();
        $goodWhere['gid']=$data['gid'];
        $good=$batteryBaseModel->name('good')->where($goodWhere)->order('id DESC')->find();
        if(!$good){
            $this->error('获取商品失败');
        }
        $morderid = 'T' . $this->getOrderId();
        $time=time();
        $md5=md5($morderid.'rWY27jftsCVkawzmUtNi2b53niWbTopU');
        $orderData = array(
            'order_id' => $morderid,
            'gid' => intval($data['gid']),
            'amount' => $good->price,
            'create_time' => $time,
            'up_time' => $time,
            'brief' => '电池',
            'car_name' => trim($data['name']),
            'car_type' => trim($data['type']),
            'car_year' => trim($data['year']),
            'car_model' =>trim($data['model']),
            'ip' => get_client_ip(),
            'md5' => $md5
        );
        $tag=$batteryBaseModel->name('order')->insert($orderData);
        if($tag){
            $this->success('请求成功','',$md5);
        }else{
            $this->error('获取失败');
        }


    }

    function details(){
        $validate = new Validate([
            'token'          => 'require',

        ]);
        $validate->message([
            'token.require'          => '参数异常',
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $this->setTitleName('订单确认');
        $batteryBaseModel=new BatteryBaseModel();
        $where['md5']=$data['token'];
        $order=$batteryBaseModel->name('order')->where($where)->find();
        if($order){
            $order->amount=bcdiv($order->amount,100,2);
            $weekArr=array("日","一","二","三","四","五","六");
            $days=array();

            for($i=0;$i<35;$i++){
                $days[$i]['time']=date("m-d",strtotime('+'.$i.'day'));
                $days[$i]['time_date']=date("Y-m-d",strtotime('+'.$i.'day'));
                if ($i==0) {
                    $days[$i]['week']= '今';
                    $days[$i]['class']= 'jin';
                }else{
                    $days[$i]['week']= $weekArr[date("w",strtotime('+'.$i.'day'))];
                }
            }

            $setdata=array();
            $str='';
            foreach ($days as $key=>$v){
                $str=$str."<td class=\"tb_item\" onclick=\"selecttime(this)\" data-time=\"{$v['time_date']}\">
                                    <div >{$v['time']}</div>
                                    <div class=\"tb_item_time\">{$v['week']}</div>
                                </td>";
                if((($key+1)%7)==0){
                    $html="<tr>".$str."</tr>";
                    array_push($setdata,array('html'=>$html));
                    $str='';
                }
            }
            $this->assign('order', $order);
            $this->assign('weekinfo', $setdata);
            $this->assign('token', trim($data['token']));
            return $this->fetch();
        }else{
            $this->error('订单信息不存在');
        }

    }

    //账单明细
    function payorder()
    {
        $validate = new Validate([
            'token'          => 'require',
            'province'          => 'require',
            'city'          => 'require',
            'area'          => 'require',
            'user_name'          => 'require',
            'user_phone'          => 'require',
            'user_addr'          => 'require',
            'select_time'          => 'require',
        ]);
        $validate->message([
            'token.require'          => '参数异常',
            'province.require'          => '用户姓名',
            'city.require'          => '用户姓名',
            'area.require'          => '用户姓名',
            'user_name.require'          => '用户姓名',
            'user_phone.require'          => '收款手机号',
            'user_addr.require'          => '用户地址',
            'select_time.require'          => '预约时间',
        ]);

        //TODO 手机校验没做
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $select_time=strtotime($data['select_time']);
        if($select_time<=0||$select_time<time()){
            $this->error('预约时间有误');
        }
        $channel_id='alipay_wap';
        $where['md5']=$data['token'];
        $batteryBaseModel=new BatteryBaseModel();
        $batteryBaseModel->startTrans();

        $order=$batteryBaseModel->name('order')->where($where)->lock(true)->find();

        $time=time();
        if($order){
            $isNotAddr=false;
            $addrss_id=0;
            if($order->addrss_id===0){
                $isNotAddr=true;
                $addmd5=md5($data['province'].$data['city'].$data['area'].$data['user_name'].$data['user_phone'].$data['user_addr']);
                $addWhere['md5']=$addmd5;
                $addrss=$batteryBaseModel->name('addrss')->where($addWhere)->find();
                if(!$addrss){
                    $dataAdd = array(
                        'name' => $data['user_name'],
                        'phone' => $data['user_phone'],
                        'province' => $data['province'],
                        'city' => $data['city'],
                        'area' => $data['area'],
                        'content' => $data['user_addr'],
                        'create_time' => $time,
                        'md5' => $addmd5
                    );
                    $addtag=$batteryBaseModel->name('addrss')->insert($dataAdd);
                    if(!$addtag){
                        $batteryBaseModel->rollback();
                        $this->error('下单失败1004');
                    }else{
                        $addrss_id=$batteryBaseModel->getLastInsID();
                    }

                }else{
                    $addrss_id=$addrss->id;
                }
            }
            $paywhere['order_id']=$order->id;
            $payorder=$batteryBaseModel->name('pay_order')->where($paywhere)->lock(true)->find();
            if($payorder){
                $this->success('请求成功','',$payorder->pay_data);
            }else{
                if($isNotAddr){
                    $orderUp['addrss_id']=$addrss_id;
                }
                $orderUp['select_time']=$select_time;
                $batteryBaseModel->name('order')->where($where)->update($orderUp);
                $dataPay = array(
                    'order_id' => $order->id,
                    'order_num' => $order->order_id,
                    'create_time' => $time,
                    'up_time' => $time,
                    'channel_id' => 1,
//                    'price' => $order->amount,
                    'price' => 1,
                    'md5' => md5( $order->id . $order->order_id . 'rWY27jftsCVkawzmUtNi2b53niWbTopU')
                );
                $tagPay = $batteryBaseModel->name('pay_order')->insert($dataPay);
                if($tagPay){
                    $pingZfPlatform=new PingZfPlatform();
                    $dataPay['success_url']=url('portal/brand','',true,true);
                    $info=$pingZfPlatform->createCharge($dataPay,'电池上门服务','alipay_wap',get_client_ip(),'');
                    if ($info) {
                        $upDataPay['up_time'] = time();
                        switch ($channel_id) {
                            case 'alipay_wap':
                                $upDataPay['pay_data'] = json_encode($info);
                                break;
                        }
                        $upwhere['id'] = $batteryBaseModel->getLastInsID();
                        $tagPay1 = $batteryBaseModel->name('pay_order')->where($upwhere)->update($upDataPay);
                        if($tagPay1){
                            $batteryBaseModel->commit();
                            $this->success('请求成功','',$upDataPay['pay_data']);
                        }else{
                            $batteryBaseModel->rollback();
                            $this->error('下单失败1002');
                        }
                    }else{
                        $batteryBaseModel->rollback();
                        $this->error('下单失败1003');
                    }
                }else{
                    $batteryBaseModel->rollback();
                    $this->error('下单失败1001');
                }
            }

        }else{
            $batteryBaseModel->rollback();
            $this->error('查询订单失败');
        }
    }


    function submint(){
        $validate = new Validate([
            'token'          => 'require',
        ]);
        $validate->message([
            'token.require'          => '参数异常',
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $this->setTitleName('订单确认');
        $batteryBaseModel=new BatteryBaseModel();
        $where['md5']=$data['token'];

        $order=$batteryBaseModel->name('order')->where($where)->find();

        if($order){
            return $this->fetch();

        }else{
            $this->error('订单信息不存在');
        }
    }

    private function getOrderId($prefix = '300')
    {
        return $prefix . (strtotime(date('YmdHis', time()))) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
    }
    
    
    



}